﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;

namespace MouseExtender.Logic.Entities
{
	[DataContract(Namespace = Constants.DataContractNamespace)]
	[KnownType(typeof(ThumbsData))]
	[KnownType(typeof(ExternalImage))]
	[KnownType(typeof(List<ExternalImage>))]
	public class ThumbsData : IEnumerable<ExternalImage>
	{
		#region fields

		[DataMember]
		private List<ExternalImage> _thumbsData;

		#endregion

		#region properties

		public bool IsEmpty
		{
			get
			{
				return _thumbsData == null || _thumbsData.Count == 0;
			}
		}

		/// <summary>
		/// Retrive or Set external image by id. If set null with specific id then item will be removed
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public ExternalImage this[string id]
		{
			[MethodImpl(MethodImplOptions.Synchronized)]
			get
			{
				ExternalImage existingImage = GetImageIfExists(id);
				return existingImage;
			}
			[MethodImpl(MethodImplOptions.Synchronized)]
			set
			{
				if (string.IsNullOrEmpty(id))
					throw new ArgumentNullException("id");

				ExternalImage existingImage = GetImageIfExists(id);

				if (value == null)
				{
					//remove item
					if (existingImage != null)
						_thumbsData.Remove(existingImage);
				}
				else
				{
					if (existingImage == null)
					{
						_thumbsData.Add(value);
					}
					else
					{
						existingImage.ImageData = value.ImageData;
						existingImage.IsImage = value.IsImage;
					}
				}
			}
		}

		#endregion

		#region constructor

		public ThumbsData()
		{
			_thumbsData = new List<ExternalImage>();
		}

		#endregion

		#region methods

		[MethodImpl(MethodImplOptions.Synchronized)]
		public void CleanupThumbs(List<LauncherItem> launcherItems)
		{
			List<ExternalImage> itemsToRemove = new List<ExternalImage>();

			foreach (ExternalImage image in _thumbsData)
			{
				//if no launcher items associated with this image then mark to remove
				if (launcherItems.Where(li => !string.IsNullOrEmpty(li.ThumbsImageId) && li.ThumbsImageId == image.Id).Count() == 0)
				{
					itemsToRemove.Add(image);
				}
			}

			foreach (ExternalImage image in itemsToRemove)
			{
				_thumbsData.Remove(image);
			}
		}

		private ExternalImage GetImageIfExists(string id)
		{
			ExternalImage existingImage = _thumbsData.Where(ei => ei.Id == id).SingleOrDefault();
			return existingImage;
		}

		#endregion

		#region IEnumerable<ExternalImage> Members

		public IEnumerator<ExternalImage> GetEnumerator()
		{
			return _thumbsData.GetEnumerator();
		}

		#endregion

		#region IEnumerable Members

		IEnumerator IEnumerable.GetEnumerator()
		{
			return _thumbsData.GetEnumerator();
		}

		#endregion
	}
}
